angular.module('ionicApp', ['ionic'])

    .config(function($stateProvider, $urlRouterProvider) {

        $stateProvider
            .state('signin', {
                url: '/sign-in',
                templateUrl: 'templates/sign-in.html',
                controller: 'SignInCtrl'
            })
            .state('forgotpassword', {
                url: '/forgot-password',
                templateUrl: 'templates/forgot-password.html'
            })
            .state('tabs', {
                url: '/tab',
                abstract: true,
                templateUrl: 'templates/tabs.html'
            })
            .state('tabs.home', {
                url: '/home',
                views: {
                    'home-tab': {
                        templateUrl: 'templates/home.html',
                        controller: 'HomeTabCtrl'
                    }
                }
            })
            .state('tabs.facts', {
                url: '/facts',
                views: {
                    'home-tab': {
                        templateUrl: 'templates/facts.html'
                    }
                }
            })
            .state('tabs.facts2', {
                url: '/facts2',
                views: {
                    'home-tab': {
                        templateUrl: 'templates/facts2.html'
                    }
                }
            })
            .state('tabs.about', {
                url: '/about',
                views: {
                    'about-tab': {
                        templateUrl: 'templates/about.html'
                    }
                }
            })
            .state('tabs.navstack', {
                url: '/navstack',
                views: {
                    'about-tab': {
                        templateUrl: 'templates/nav-stack.html'
                    }
                }
            })
            .state('tabs.order', {
                url: '/order/:user_id/:access_token',
                views: {
                    'order-tab': {
                        templateUrl: 'templates/order.html',
                        controller: 'OrderListCtrl'
                    }
                }
            })
            .state('tabs.detail', {
                url: '/order/:servant_id/detail/:order_id',
                views: {
                    'order-tab': {
                        templateUrl: 'templates/detail.html',
                        controller: 'OrderDetailCtrl'
                    }
                }
            });


        $urlRouterProvider.otherwise('/tab/home');

    })

    .controller('SignInCtrl', function($scope, $state) {

        $scope.signIn = function(user) {
            console.log('Sign-In', user);
            $state.go('tabs.home');
        };

    })
    .factory('orderService', ['$http', '$location', function ($http, $location) {
        return {

            list: function(wechat_qy_account, data, app_id, fn) {
                var param = {
                    start_time:(data != ''&& data != undefined)?data.start_time:'',
                    end_time:(data != ''&& data != undefined)?data.end_time:'',
                    card_number:(data != ''&& data != undefined)?data.card_number:'',
                    company:(data != ''&& data != undefined)?data.company:'',
                    status:(data != ''&& data != undefined)?data.status:'',
                    score:(data != ''&& data != undefined)?parseInt(data.score):'',
                    serviceType1:(data != ''&& data != undefined && data.serviceType1!=undefined)?data.serviceType1:'',
                    serviceType2:(data != ''&& data != undefined && data.serviceType2!=undefined)?data.serviceType2:'',
                    serviceType3:(data != ''&& data != undefined && data.serviceType3!=undefined)?data.serviceType3:'',
                    order_id:(data != ''&& data != undefined)?data.order_id:'',
                    name:(data != ''&& data != undefined)?data.username:'',
                    address:(data != ''&& data != undefined)?data.address:'',
                    phone:(data != ''&& data != undefined)?data.phone:''
                };

                baas_jz.call({
                    'http': $http,
                    'method': 'get',
                    //'uri': 'order/orderList/wechat/count/'+code,
                    //'uri': 'order/orderList/count',
                    'uri' : 'order/orderList/servant/'+wechat_qy_account,
                    'data' : param,
                    'success': function(d) {
//                  $scope.list = d.list;
                        //console.log(d);
                        if (typeof fn == 'function') {
                            fn(d);
                        }
                    }
                });
            }
            ,find_one : function( order_id, fn ){
                baas_jz.call({
                    'http': $http,
                    'method': 'post',
                    'uri' : 'order/orderList/info',
                    'data' : {
                        order_id : order_id
                    },
                    'success': function(d) {
//                  $scope.list = d.list;
                        //console.log(d);
                        if (typeof fn == 'function') {
                            fn(d);
                        }
                    }
                });
            }
            ,find_card : function( card_number, fn ){
                baas_yl.call({
                    'http': $http,
                    'method': 'post',
                    'uri' : 'card/index/searchCard',
                    'data' : {
                        card_id : card_number
                    },
                    'success': function(d) {
//                  $scope.list = d.list;
                        //console.log(d);
                        if (typeof fn == 'function') {
                            fn(d);
                        }
                    }
                });
            },
            signIn: function (data, fn) {
                var servantId = typeof data.servant_id === 'undefined' || !data.servant_id ? '' : data.servant_id;
                var param = {
                    order_id: typeof data.order_id === 'undefined' || !data.order_id ? '' : data.order_id,
                    longitude: typeof data.longitude === 'undefined' || !data.longitude ? '' : data.longitude,
                    latitude: typeof data.latitude === 'undefined' || !data.latitude ? '' : data.latitude,
                    type: '签到',
                    description: typeof data.description === 'undefined' || !data.description ? '' : data.description,
                    attribute: typeof data.attribute === 'undefined' ? {} : data.attribute
                };
                baas_yl.call({
                    http: $http,
                    method: 'post',
                    uri: 'servant/servant/signin/' + servantId,
                    data: param,
                    success: function (json) {
                        if (typeof fn === 'function') {
                            fn(json);
                        }
                    }
                });
            },
            signOut: function (data, fn) {
                var servantId = typeof data.servant_id === 'undefined' || !data.servant_id ? '' : data.servant_id;
                var signId = typeof data.sign_id === 'undefined' || !data.sign_id ? '' : data.sign_id;
                var param = {
                    type: '签出',
                    description: typeof data.description === 'undefined' || !data.description ? '' : data.description
                };
                baas_yl.call({
                    http: $http,
                    method: 'post',
                    uri: 'servant/servant/signout/' + signId + '/' + servantId,
                    data: param,
                    success: function (json) {
                        if (typeof fn === 'function') {
                            fn(json);
                        }
                    }
                });
            },
            listSignItem: function (data, fn) {
                var param = data;
                /*var param = {
                 servant_id: typeof data.servant_id === 'undefined' || !data.servant_id ? '' : data.servant_id,
                 order_id: typeof data.order_id === 'undefined' || !data.order_id ? '' : data.order_id,
                 servant_name: typeof data.servant_name === 'undefined' || !data.servant_name ? '' : data.servant_name,
                 type: typeof data.type === 'undefined' || (data.type !== '签到' && data.type !== '签出') ? '' : data.type,
                 status: typeof data.status === 'undefined' || !data.status ? '' : data.status,
                 start_time: typeof data.start_time === 'undefined' || !data.start_time ? '' : data.start_time,
                 end_time: typeof data.end_time === 'undefined' || !data.end_time ? '' : data.end_time
                 };*/
                baas_yl.call({
                    http: $http,
                    method: 'get',
                    uri: 'servant/servant/sign/list',
                    data: param,
                    success: function (json) {
                        if (typeof fn === 'function') {
                            fn(json);
                        }
                    }
                });
            },
            deleteSignItem: function (data, fn) {
                var signId = typeof data.sign_id === 'undefined' || !data.sign_id ? '' : data.sign_id;
                baas_yl.call({
                    http: $http,
                    method: 'get',
                    uri: 'servant/servant/sign/delete/' + signId,
                    success: function (json) {
                        if (typeof fn === 'function') {
                            fn(json);
                        }
                    }
                });
            }
        };
    }])

    .controller('OrderListCtrl', function($location,  $scope, $state, $timeout, $ionicPopup ,$rootScope,orderService) {
        //$scope.items = ['Item 1', 'Item 2', 'Item 3']

        var user_id = $state.params.user_id;
        var access_token = $state.params.access_token;
        localStorage.setItem('user_id',user_id);
        localStorage.setItem('access_token',access_token);
        console.log($location.search());

        if( typeof $location.search().state != 'undefined' ){
            localStorage.setItem('state', $location.search().state);
            $rootScope.state = $location.search().state;
        }

        $scope.state  = $rootScope.state ;
        $scope.showPopup = function() {
            $scope.data = {}

            // An elaborate, custom popup
            var myPopup = $ionicPopup.show({
                template: '<input type="text" ng-model="data.card_number">',
                title: '请输入会员卡号',
                subTitle: '',
                scope: $scope,
                buttons: [
                    { text: '取消' },
                    {
                        text: '<b>查询</b>',
                        type: 'button-positive',
                        onTap: function(e) {
                            if (!$scope.data.card_number) {
                                //don't allow the user to close unless he enters wifi password
                                e.preventDefault();
                            } else {

                                $scope.data.status = "已接单";
                                $scope.getList();
                            }
                        }
                    },
                ]
            });
            myPopup.then(function(res) {
                console.log('Tapped!', res);
            });
        };
        if($scope.state == 'scan'){
            $scope.showPopup();
        }



        $scope.getList = function(){

            orderService.list(user_id, $scope.data, $scope.app_id, function(json) {
                $scope.list = json.list;
                localStorage.setItem('scan_time', json.callTime );
                $scope.$broadcast('scroll.refreshComplete');
            });
        };

        if($scope.state != 'scan') {

            $scope.getList();
        }

        $scope.doRefresh = function() {
//		    console.log('Refreshing!');
            $timeout( function() {
                //simulate async response
                //$scope.items.push('New Item ' + Math.floor(Math.random() * 1000) + 4);
                //Stop the ion-refresher from spinning

                $scope.getList();
            }, 1000);
        };

    })
    .controller('OrderDetailCtrl', function($window,$location,$scope,$state, $http, $stateParams, $timeout,$rootScope,orderService, $ionicPopup, $ionicLoading) {
        //获取经纬度
        $scope.getCoords = function (fn) {
            var geolocation = window.navigator.geolocation;
            var latitude = 0, longitude = 0, message = '';
            if (geolocation) {
                geolocation.getCurrentPosition(function (position) {
                    latitude = position.coords.latitude;
                    longitude = position.coords.longitude;
                    message = '已成功获取您的位置信息';
                    if (typeof fn === 'function') {
                        fn({
                            lat: latitude,
                            lng: longitude,
                            msg: message
                        });
                    }
                }, function (error) {
                    switch (error.code) {
                        case error.TIMEOUT:
                            message = '连接超时，请重试';
                            break;
                        case error.PERMISSION_DENIED:
                            message = '您拒绝了使用位置共享服务，查询已取消';
                            break;
                        case error.POSITION_UNAVAILABLE:
                            message = '非常抱歉，暂时无法通过浏览器获取您的位置信息';
                            break;
                        default:
                            message = '非常抱歉，暂时无法通过浏览器获取您的位置信息';
                            break;
                    }
                    if (typeof fn === 'function') {
                        fn({
                            lat: latitude,
                            lng: longitude,
                            msg: message
                        });
                    }
                }, {enableHighAccuracy: true});
            }
        };
        $scope.getCoords(function (obj) {
            $scope.latitude = obj.lat;
            $scope.longitude = obj.lng;
            $scope.message = obj.msg;
            console.log(obj);
        });

        //签入签出
        $scope.signIn = function () {
            $scope.data = {};
            var popup = $ionicPopup.show({
                template: '<textarea rows="3" style="resize: vertical;" ng-model="data.info">',
                title: '签入',
                subTitle: '请输入签入备注',
                scope: $scope,
                buttons: [
                    {
                        text: '确定',
                        type: 'button-balanced',
                        onTap: function (e) {
                            if (!$scope.data.info) {
                                e.preventDefault();
                            } else {
                                return $scope.data;
                            }
                        }
                    },
                    {
                        text: '取消',
                        type: 'button-light'
                    }
                ]
            });
            popup.then(function (res) {
                if (res) {
                    $ionicLoading.show({
                        template: '<i class="icon ion-load-a"></i> Loading...'
                    });
                    var data = {
                        servant_id: $scope.item.selected_servant_id,
                        order_id: $scope.item.order_id,
                        longitude: $scope.longitude,
                        latitude: $scope.latitude,
                        description: res.info
                    };
                    orderService.signIn(data, function (json) {
                        if (json.status) {
                            $ionicLoading.show({
                                template: '<i class="icon ion-checkmark-circled"></i> 签入成功',
                                duration: 1000
                            });
                        } else {
                            $ionicLoading.show({
                                template: '<i class="icon ion-alert-circled"></i> 签入失败',
                                duration: 2000
                            });
                        }
                    });
                }
            });
            $timeout(function () {
                $ionicLoading.hide();
                popup.close();
            }, 30000);
        };
        $scope.signOut = function () {
            $scope.data = {};
            var popup = $ionicPopup.show({
                template: '<textarea rows="3" style="resize: vertical;" ng-model="data.info">',
                title: '签出',
                subTitle: '请输入签出备注',
                scope: $scope,
                buttons: [
                    {
                        text: '确定',
                        type: 'button-balanced',
                        onTap: function (e) {
                            if (!$scope.data.info) {
                                e.preventDefault();
                            } else {
                                return $scope.data;
                            }
                        }
                    },
                    {
                        text: '取消',
                        type: 'button-light'
                    }
                ]
            });
            popup.then(function (res) {
                if (res) {
                    $ionicLoading.show({
                        template: '<i class="icon ion-load-a"></i> Loading...'
                    });
                    var baseDate = new Date().getFullYear() + '-' + (new Date().getMonth() + 1) + '-' + new Date().getDate();
                    var data = {
                        servant_id: $scope.item.selected_servant_id,
                        order_id: $scope.item.order_id,
                        start_time: baseDate + ' 00:00:00',
                        end_time: baseDate + ' 23:59:59'
                    };
                    orderService.listSignItem(data, function (json) {
                        if (json.count) {
                            data = {
                                servant_id: '',
                                sign_id: '',
                                description: res.info
                            };
                            for (var i = 0, len = json.list.length; i < len; i++) {
                                if (json.list[i].type == '签到') {
                                    data.servant_id = json.list[i].servant_id;
                                    data.sign_id = json.list[i].sign_id;
                                    break;
                                }
                            }
                            orderService.signOut(data, function (json) {
                                if (json.status) {
                                    $ionicLoading.show({
                                        template: '<i class="icon ion-checkmark-circled"></i> 签出成功',
                                        duration: 1000
                                    });
                                } else {
                                    $ionicLoading.show({
                                        template: '<i class="icon ion-alert-circled"></i> 签出失败',
                                        duration: 2000
                                    });
                                }
                            });
                        }
                    });
                }
            });
            $timeout(function () {
                $ionicLoading.hide();
                popup.close();
            }, 30000);
        };

        var order_id = $stateParams.order_id;
        $scope.state = $rootScope.state ;
        $scope.toNumber = function( thisValue, defaultNumber ){

            var res = thisValue != undefined ? parseInt( thisValue ) : defaultNumber;
            res = !isNaN( res ) ? res : defaultNumber;
            return res;
        };

        $scope.getServiceType = function( item ){
            $scope.item.serviceType = '';
            if( $scope.item.serviceType1_title != undefined && $scope.item.serviceType1_title.length > 0 ){
                $scope.item.serviceType = $scope.item.serviceType1_title;
            }
            if( $scope.item.serviceType2_title != undefined && $scope.item.serviceType2_title.length > 0 ){
                $scope.item.serviceType += ' > ' + $scope.item.serviceType2_title ;
            }
            if( $scope.item.serviceType3_title != undefined && $scope.item.serviceType3_title.length > 0 ){
                $scope.item.serviceType += ' > ' + $scope.item.serviceType3_title ;
            }
        };

        $scope.find_one = function(){
            orderService.find_one(order_id , function(json) {
                $scope.item = json.orderinfo;
                $scope.item.finish_button = 'not_click'; // 初始化完成按钮
                if( $scope.item.card_number != undefined ){
                    $scope.card = {};
                    $scope.findCard( $scope.item.card_number );
                }
                console.log($scope.item);

            });
        };
        $scope.find_one();
        $scope.findCard = function( card_number ){

            orderService.find_card(card_number , function(json) {
                if( json.length > 0){
                    $scope.card = json[0];
                }else{
                    $scope.card.fund = 0;
                    console.log('老年卡不存在');
                }
                $scope.initData();
            });
        };
        $scope.initData = function(){

            //单位价格
            $scope.item.settlement_price = $scope.toNumber( $scope.item.settlement_price, 0);
            // 单位次数
            $scope.item.settlement_service_times = $scope.toNumber( $scope.item.settlement_service_times, 1);
            //额外追加的钱
            if( $scope.item.settlement_extraPrice >= 0 ){
                $scope.item.extraPriceFlag = 'add';
                $scope.item.settlement_extraPrice_add = $scope.item.settlement_extraPrice;
                $scope.item.settlement_extraPrice_reduce = 0;
            }else{
                $scope.item.extraPriceFlag = 'reduce' ;
                $scope.item.settlement_extraPrice_reduce = Math.abs( $scope.item.settlement_extraPrice );
                $scope.item.settlement_extraPrice_add = 0;
            }
            $scope.item.settlement_extraPrice = $scope.toNumber( $scope.item.settlement_extraPrice, 0);

            $scope.getServiceType( $scope.item );//$scope.state = 'scan'; $scope.item.status='已接单'; $scope.item.settlement_status=0;
            //结算完成
            if( typeof $scope.item.settlement_status != 'undefined' &&
                $scope.item.settlement_status == 1 ){
                $scope.settlement_status = 1;
                //老人卡支付的钱
                $scope.item.settlement_card_fund = $scope.toNumber( $scope.item.settlement_card_fund, 0);
                //支付的现金
                $scope.item.settlement_cash = $scope.toNumber( $scope.item.settlement_cash, 0);
                $scope.item.settlement_total = $scope.toNumber( $scope.item.settlement_total, 0);
            }else{
                $scope.settlement_status = 0;
                $scope.getPriceTotal( $scope.item );
            }
            //$scope.settlement_status = 1;
        };

        //todo 老人卡支付 生成交易
        $scope.createTransaction = function( data, fn ) {

            baas_yl.call({
                'http': $http,
                'method': 'post',
                'uri': 'card/index/transaction/' + data.card_number ,
                'data': {
                    type : 'pay',
                    fund : data.settlement_card_fund,
                    description : '微信企业号扣款',
                    shop : '80岁老人',
                    status : '1',
                    'transaction_operator' : '从业人员:' + data.selected_servant_name + '|' + data.selected_servant_id
                },
                'success': function (json) {
                    if (typeof fn == 'function' && json.status ) {
                        data.transaction_no = json.transaction_no;
                        fn( data );
                    }

                }

            });
        };

        // 调用完成订单API
        $scope.finish = function( data ){

            var lat = localStorage.getItem('latitude');
            var lng = localStorage.getItem('longitude');
            var paramsData = {
                selected_servant_lat : lat,
                selected_servant_lng : lng,
                start_time : localStorage.getItem('scan_time'),
                settlement_service_times : data.settlement_service_times,
                settlement_extraPrice : data.settlement_extraPrice,
                charge_operator : '从业人员:' + data.selected_servant_name + '|' + data.selected_servant_id,
                'pay':1
            };
            if( typeof data.transaction_no != 'undefined' ){
                paramsData.transaction_no = data.transaction_no;
            }

            baas_jz.call({
                'http': $http,
                'method': 'post',
                'uri': 'order/order/servant/' + data.selected_servant_id + '/finish/'+data.order_id,
                'data' : paramsData,

                'success': function(d) {
                    if(d.status){
                        alert("更新成功");
                        //$location.path( '/tab/order' );
                        //$location.url();
                        $scope.item.status = '完成';
                        $scope.find_one( $scope.order_id );
                    }else{
                        alert(d.description);
                    }
                }
            });
        };

        // 页面完成订单按钮动作
        $scope.update = function( data ){
            if( data.settlement_total <= 0 ){
                alert( '总价必须大于零' );
                return;
            }
            data.finish_button = 'clicked';
            if(typeof $scope.card.card_id != 'undefined' && data.settlement_card_fund > 0 ){
                $scope.createTransaction( data, $scope.finish );
            }else{
                $scope.finish( data );
            }


        };

        $scope.extra_price_edit_status = 0;
        $scope.checkExtraPrice = function( item ){
            $scope.extra_price_edit_status = 0;
            $scope.getPriceTotal( item );
        };
        $scope.setExtraPrice = function(  ){
            $scope.extra_price_edit_status = 1;
        };

        $scope.changeExtraPrice = function( flag ){
            $scope.item.extraPriceFlag = flag;
            $scope.getPriceTotal($scope.item);
        };

        $scope.getPriceTotal = function( item ){

            item.settlement_extraPrice = item.extraPriceFlag == 'add' ?
                item.settlement_extraPrice_add : item.settlement_extraPrice_reduce;
            item.settlement_extraPrice = $scope.toNumber(item.settlement_extraPrice,0);
            item.settlement_extraPrice = item.extraPriceFlag == 'add' ?
                item.settlement_extraPrice  : - item.settlement_extraPrice;

            item.settlement_total = item.settlement_price * item.settlement_service_times + item.settlement_extraPrice;
            item.settlement_cash = item.settlement_total - parseInt( $scope.card.fund ); // 现金

            if( item.settlement_cash < 0 ){
                item.settlement_cash = 0;
                item.settlement_card_fund = item.settlement_total;
            }else{
                item.settlement_card_fund = $scope.card.fund;
            }


        };
        /**
         * 修改服务价格
         */
        $scope.updateServiceTimes = function( item, sign ){

            if( sign == '+' ){
                item.settlement_service_times ++;
            }else{
                item.settlement_service_times --;
            }
            item.settlement_service_times = item.settlement_service_times > 0 ?
                item.settlement_service_times : 1;
            $scope.getPriceTotal( item );
        };
    })

    .controller('HomeTabCtrl', function($scope,$ionicPopup) {
        console.log('HomeTabCtrl');

    });